package org.example.seata.common.feign.config;

import feign.Feign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.stereotype.Component;

/**
 * 微服务之间调用传递token
 * 支持微服务之间无token调用
 *
 * @author hzq
 * @date 2021/12/17 17:45
 */
@Slf4j
@Component
@ConditionalOnClass({Feign.class, OAuth2ClientContext.class})
@ConditionalOnProperty(value = "feign.oauth2.enabled", matchIfMissing = true)
@ConditionalOnBean({OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class})
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class CustomOAuth2FeignRequestInterceptor extends OAuth2FeignRequestInterceptor {

    public CustomOAuth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails resource) {
        super(oAuth2ClientContext, resource);
    }

    @Override
    protected String extract(String tokenType) {
        try {
            return super.extract(tokenType);
            // 提取token失败 支持微服务之间无token调用
        } catch (UserRedirectRequiredException e) {
            // ignored
            log.warn(e.getLocalizedMessage());
        } catch (AuthenticationException e) {
            // ignored
            log.warn(e.getLocalizedMessage());
        }
        return null;
    }
}
